// pages/send/send.js
let name = ''
let phone = ''
let price = ''
let abstract = ''
let imgaddress = ''
let inventory = ''
let type = ''
let openid = ""
let imgPATH = ''
let imgpath1 = ''
let imgpath2 = ''
let imgpath3 = ''
let imgpath4 = ''
let imgpath5 = ''
let imgpath6 = ''
let imgpath7 = ''
let imgpath8 = ''
let imgpath9 = ''
let IMGNUM = 0
var imgPath
let filePatH = []
let username = ''
let userIMG = ''
let touxiang = ''
let NAME = ''
let Address = ''
let unit = ''
let distribution = ''
let province = ''
let city = ''
let district = ''
let Alladdress = ''
let longitude = '' //经度
let latitude = '' //纬度
Page({
  data: {
    show: false,
    show1: true,
    show3: false,
    show4: true,
    checked: '',
    disabled: true,
    TY: '',
    fileList: [],      //存放有图片地址的图片数组
    linshi: [],  //存放选择的图片的临时数组
    types1: [
      { value: '1', name: '居家用品', checked: 'true' },
      { value: '2', name: '家具家电' },
      { value: '3', name: '智能设备' },
      { value: '4', name: '美妆养护' },
      { value: '5', name: '运动用品' },
      { value: '6', name: '汽车用品' },
      { value: '7', name: '宠物用品' },
      { value: '8', name: '食品零食' },
      { value: '9', name: '娱乐游戏' },
    ],
    types2: [
      { value: '10', name: '家居保洁' },
      { value: '11', name: '空调清洗' },
      { value: '12', name: '油烟机清洗' },
      { value: '13', name: '环境防护' }
    ],
    types3: [
      { value: '14', name: '用水维修' },
      { value: '15', name: '用电维修' },
      { value: '16', name: '家电维修' },
      { value: '17', name: '家具维修' }
    ],
    types4: [
      { value: '18', name: '1人拼车' },
      { value: '19', name: '2人拼车' },
      { value: '20', name: '3人拼车' },
      { value: '21', name: '多人拼车' }
    ],
    types5: [
      { value: '22', name: '时令水果' },
      { value: '23', name: '粮油调味' },
      { value: '24', name: '休闲食品' },
      { value: '25', name: '饮料酒水' },
      { value: '26', name: '冷冻冷藏' },
      { value: '27', name: '日用百货' },
    ],
    types6: [
      { value: '28', name: '废品回收' },
      { value: '29', name: '衣物回收' },
      { value: '30', name: '旧物回收' },
    ],
    types7: [
      { value: '31', name: '早教幼儿' },
      { value: '32', name: '主课教培' },
      { value: '33', name: '兴趣教培' },
      { value: '34', name: '职业教培' },
    ],
    types8: [
      { value: '35', name: '快餐小吃' },
      { value: '36', name: '米粉面馆' },
      { value: '37', name: '面包蛋糕' },
      { value: '38', name: '火锅烧烤' },
      { value: '39', name: '饮品甜品' },
      { value: '40', name: '特色菜品' },
    ],
    types9: [
      { value: '41', name: '日常养护' },
      { value: '42', name: '美甲美睫' },
      { value: '43', name: '按摩推拿' },
      { value: '44', name: '皮肤管理' },
    ],
    types10: [
      { value: '45', name: '洗剪吹' },
      { value: '46', name: '洗头养护' },
      { value: '47', name: '烫染造型' },
    ],
    types11: [
      { value: '48', name: '洗车美容' },
      { value: '49', name: '保养维修' },
      { value: '50', name: '汽车改装' },
    ],
    types12: [
      { value: '51', name: '日常养护' },
      { value: '52', name: '体检医疗' },
    ]
  },
  onLoad() {
    this.getopenid()
  },
  show() {
    this.setData({
      show: true,
      show1: false
    })
  },
  show2() {
    this.setData({
      show3: true,
      show4: false
    })
  },
  toclause:function() {
    wx.navigateTo({
      url: '/pages/clause/clause',
    })
  },
  getopenid() {
    wx.cloud.callFunction({
      name: 'getOPENID'
    })
      .then(res => {
        console.log('成功获取openID', res)
        this.setData({
          openid: res.result.openid
        })
        openid = res.result.openid
        this.getaddress()
        this.getUserProfile()
      })
      .catch(res => {
        console.log('失败', res)
      })
  },
  getaddress() {
    wx.cloud.database().collection('Address')
      .where({
        openid: openid
      })
      .get()
      .then(res => {
        if (Object.keys(res.data).length == 0) {
          wx.showToast({
            title: '请先选择您的位置',
            icon: 'none',
            duration: 1000,
            success: function () {
              setTimeout(function () {
                wx.reLaunch({
                  url: '/pages/home/home',
                })
              }, 1000);
            }
          })
        } else {
          console.log('res:', res)
          Address = res.data[0].address
          province = res.data[0].province
          city = res.data[0].city
          district = res.data[0].district
          Alladdress = res.data[0].address
          longitude= res.data[0].longitude
          latitude = res.data[0].latitude
        }
      })
      .catch(err => {

      })
  },
  //获取头像姓名
  getUserProfile() {
    wx.cloud.database().collection('user-information')
      .where({
        _openid: openid
      })
      .get()
      .then(res => {
        NAME = res.data[0].NAME
        touxiang = res.data[0].image
        console.log('用户信息获取成功', res)
      })
      .catch(err => {
        console.log('用户信息查询失败', err)
      })
  },
  //类型选择
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    let str = e.detail.value
    let arr = str.split('-')
    type = arr[0]
    this.setData({
      TY: arr[1],
      show: false,
      show1: true
    })
  },
  //  配送方式选择
  distributionChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      distribution: e.detail.value,
      show3: false,
      show4: true
    })
    distribution = e.detail.value
  },
  check(e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    let val = e.detail.value
    if (val.length > 0) {
      this.setData({
        checked: true,
        disabled: false
      })
    } else {
      this.setData({
        checked: false,
        disabled: true
      })
    }
  },
  // ------------------------------------图片上传代码--------------------------------------
  uploadToCloud() {
    let that = this;
    wx.chooseImage({
      count: 9,         //count属性确定最多可以上传9张，下方属性可以看看官方的说明，就不一一说明
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '正在上传',
        })
        //赋值给linshi临时数组暂时存储起来
        that.setData({
          linshi: that.data.linshi.concat(res.tempFilePaths)
        })
        console.log('-------------临时地址数组为-------------')
        console.log('选择的图片临时数组为：', that.data.linshi)
        console.log('-------------临时地址数组为-------------')
        //设置图片存储到云存储的位置和图片名称
        let lujin = "send-img/user/" + openid + "/" + new Date().getTime() + "-" + Math.floor(Math.random() * 1000);
        //这里调用了图片上传函数wx.cloud.uploadFile()
        //传给wx.cloud.uploadFile的cloudPath属性的值不能重复！！！巨坑，加个index就可以避免重复了
        const uploadTasks = that.data.linshi.map((item, index) => that.uploadFilePromise(lujin + index, item));
        //promise.all方法会等待map方法都执行完全后再继续执行then方法里面的代码
        Promise.all(uploadTasks)
          .then(data => {
            console.log(data)
            wx.hideLoading()
            wx.showToast({
              title: '上传成功',
              icon: 'none'
            });
            const newFileList = data.map(item => ({ url: item.fileID, isImage: true, }));
            imgPath = data.map(item => ({ url: item.fileID, }));
            console.log('-------------图片增量数组为-------------')
            console.log("newFileList为:", newFileList)
            console.log('-------------图片增量数组为-------------')
            //每次上传成功后，都要清空一次临时数组，避免第二次重复上传，浪费存储资源，
            that.setData({
              fileList: that.data.fileList.concat(newFileList),
              linshi: [],
            });
          })
          .catch(e => {
            wx.showToast({ title: '上传失败', icon: 'none' });
            console.log(e);
          });
      }
    })
  },
  //上传到云存储，并且获得图片地址
  uploadFilePromise(fileName, chooseResult) {
    console.log('图片地址为:', chooseResult)
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult
    });
  },
  //删除图片
  delete: function (event) {
    let that = this;
    console.log('event是：', event)
    let inde = event.currentTarget.dataset.id
    console.log('fileList[' + inde + ']是：', that.data.fileList[inde])
    let imgpath = that.data.fileList[inde].url
    //删除存储中的图片
    wx.cloud.deleteFile({
      fileList: [imgpath]
    }).then(res => {
      console.log('文件删除成功:', res.fileList)
    }).catch(error => {
      console.log('文件删除失败：', error)
    })
    //删除数组里面的值
    that.data.fileList.splice(inde, 1)
    that.setData({
      fileList: that.data.fileList,
    })
    console.log("filelist：", that.data.fileList)
    IMGNUM--
  },
  //预览图片
  previewImage: function (event) {
    console.log(event)
    wx.previewImage({
      urls: [event.currentTarget.dataset.url] // 需要预览的图片http链接列表
    })
  },
  // ------------------------------------图片上传代码--------------------------------------
  //获取用户输入的商品名
  getName(e) {
    name = e.detail.value
  },
  getphone(e){
    phone = e.detail.value
    console.log('phone:',phone)
  },
  //获取用户输入的价格
  getPrice(e) {
    price = e.detail.value
  },
  //获取用户输入的简介
  getabstract(e) {
    abstract = e.detail.value
  },
  //获取用户输入的库存
  getinventory(e) {
    inventory = e.detail.value
  },
  //获取用户输入的单位
  getUnit(e) {
    unit = e.detail.value
  },
  //添加商品到数据库
  addGood() {
    if (name == '') {
      wx.showToast({
        icon: 'error',
        title: '商品名不能为空',
      })
    } else if (abstract == '') {
      wx.showToast({
        icon: 'error',
        title: '简介不能为空',
      })
    } else if (this.data.fileList.length == 0) {
      wx.showToast({
        icon: 'error',
        title: '图片不能为空',
      })
    } else if (type == '') {
      wx.showToast({
        icon: 'error',
        title: '类型不能为空',
      })
    } else if (price == '') {
      wx.showToast({
        icon: 'error',
        title: '价格不能为空',
      })
    } else if (price < 1) {
      wx.showToast({
        icon: 'error',
        title: '价格不能低于1元',
      })
    } else if (unit == '') {
      wx.showToast({
        icon: 'error',
        title: '单位不能为空',
      })
    } else if (inventory == '') {
      wx.showToast({
        icon: 'error',
        title: '库存不能为空',
      })
    } else if (distribution == '') {
      wx.showToast({
        icon: 'error',
        title: '配送方式不能为空',
      })
    } else if (phone == '') {
      wx.showToast({
        icon: 'error',
        title: '联系方式不能为空',
      })
    } else if (this.data.checked == false) {
      wx.showToast({
        icon: 'error',
        title: '请先同意发布规范',
      })
    } else {
      //可以进行添加
      //添加商品调这个，传两个商品参数
      let that = this;
      wx.cloud.database().collection('send-Goods')
        .add({
          data: {
            name: name,
            price: parseInt(price),
            abstract: abstract,
            inventory: inventory,
            openID: openid,
            type: parseInt(type),
            NAME: NAME,
            TOUXIANG: touxiang,
            imgpath: that.data.fileList,
            unit: unit,
            distribution: distribution, //配送方式
            Address: Address,
            province:province,
            city:city,
            district:district,
            Alladdress:Alladdress,
            longitude:longitude, //经度
            latitude:latitude,  //纬度
            phone:phone
          }
        })
        .then(res => {
          //添加成功
          IMGNUM = 0
          console.log('添加成功', res)
          wx.showToast({
            title: '发布成功',
          })
          wx.reLaunch({
            url: '/pages/user/user'
          })
        })
        .catch(res => {
          //添加失败
          console.log('添加失败', res)
        })
      //添加图片地址
    }
  },
})